/*
 * @Description:
 * @Autor: lcz
 * @Date: 2023-06-09 18:34:30
 * @LastEditors: lcz
 * @LastEditTime: 2023-07-03 17:25:25
 */
import React, { useEffect, useState, Key, useMemo } from 'react';
import TreeComponent from '../../components/TreeComponent';
import type { TreeProps } from 'antd/es/tree';
import MockProps from './props';
import _ from 'lodash';
let jsonData = [
  { key: 1, parentId: 0, title: '一级菜单A' },
  { key: 2, parentId: 0, title: '一级菜单B' },
  { key: 3, parentId: 0, title: '一级菜单C' },
  { key: 4, parentId: 1, title: '二级菜单A-A' },
  { key: 5, parentId: 1, title: '二级菜单A-B' },
  { key: 6, parentId: 2, title: '二级菜单B-A' },
  { key: 7, parentId: 4, title: '三级菜单A-A-A' },
  { key: 8, parentId: 7, title: '四级菜单A-A-A-A' },
  { key: 9, parentId: 8, title: '五级菜单A-A-A-A-A' },
];

type checked = { checked: Key[]; halfChecked: Key[] };

const TreePwd: React.FC = props => {
  const [treeData, setTreeData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState<Key[]>(MockProps.selectKey ? MockProps.selectKey : []);

  //扁平化数据转树结构
  const formatTree = (obj: any): any => {
    let copyedObj = JSON.parse(JSON.stringify(obj)); //深拷贝源数据
    return copyedObj.filter((parent: any) => {
      let findChildren = copyedObj.filter((child: any) => {
        return parent.key === child.parentId;
      });
      findChildren.length > 0 ? (parent.children = findChildren) : (parent.children = []);
      return parent.parentId == 0; //返回顶层，依据实际情况判断这里的返回值
    });
  };

  // 点击选中
  const onCheck: TreeProps['onCheck'] = (data, info) => {
    console.log(data, info, 'check');
    if (MockProps.isCheckBox) {
      setCheckedKeys(data as Key[]);
    } else {
      const checked: Key[] = (data as checked).checked;
      setCheckedKeys([checked[checked.length - 1]]);
    }
  };

  // useEffect(() => {
  //   console.log(checkedKeys, 2233)
  // }, [checkedKeys])

  useEffect(() => {
    setTreeData(formatTree(jsonData));
  }, []);

  const defaultExpandedKeys = useMemo(() => {
    if (treeData.length > 0 && MockProps.selectKey) {
      let ExpandedKeys = jsonData.filter(i => MockProps.selectKey.includes(i.key)).map(i => i.parentId) ?? [];
      return _.uniq(ExpandedKeys)
    }
    return [] as Key[];
  }, [treeData, MockProps.selectKey]);

  return (
    <div style={{border:'1px solid red'}}>
      {treeData.length > 0 ? (
        <TreeComponent
          treeData={treeData}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          defaultExpandedKeys={defaultExpandedKeys}
          {...MockProps}
        ></TreeComponent>
      ) : null}
    </div>
  );
};

export default TreePwd;
